/**
 * 计时器挂件第二层: 帷幕 (原名: 感知层)
 * 
 * 大型背景的动画, 在接收到开始、停止等信号的一瞬间时的补充动画。
 * 在文字层上方
 */

class Curtain {

  // config
  parent = null;
  zrender = null;
  zrInstance = null;

  // UI
  blocks = null;
  column = 0; // l2_width
  row = 0; // l2_height

  constructor(options) {
    this.parent = options.parent;
    this.zrender = options.zrender;
    this.zrInstance = options.zrInstance;

    let {blocks, column, row} =
      drawInit(this.parent.width, this.parent.height, this.zrender, this.zrInstance);
    this.blocks = blocks;
    this.column = column;
    this.row = row;
  };

  // 启动动画
  animate() {
    for (let x = 0; x < this.column; x++) {
      let delay = Math.abs(parseInt(this.column / 2) - x) * 30;
      for (let y = 0; y < this.row; y++) {
        let el = this.blocks[x][y];
        el.stopAnimation();

        el.animate('style', false)
          .delay(delay)
          .when(100, {
            opacity: 1
          }).when(600, {
            opacity: 0.8
          }).when(1800 + parseInt(Math.random() * 800), {
            opacity: 0
          }).start('quadraticOut');
      }
    }
  };

  tick() {
    // no-thing
  };

  destroy() {
    // no-thing
  };
}

function drawInit(canvasWidth, canvasHeight, zrender, zr) {
  let column = Math.ceil(canvasWidth / 16);
  let widthOffset = parseInt((canvasWidth - column * 16) / 2);

  let row = Math.ceil(canvasHeight / 16);
  let heightOffset = parseInt((canvasHeight - row * 16) / 2);

  let blocks = [];
  for (let i = 0; i < column; i++) {
    let x = widthOffset + i * 16;
    blocks.push([]);
    for (var j = 0; j < row; j++) {
      let y = heightOffset + j * 16;

      let rect = new zrender.Rect({
        shape: {
          width: 16,
          height: 16
        },
        style: {
          fill: '#FFF',
          opacity: 0
        },
        position: [x, y],
        z: 4
      });

      blocks[i].push(rect);
      zr.add(rect);
    }
  }

  return {blocks, column, row};
}

export default Curtain;
